﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BhvCameraFollow : MonoBehaviour
{
    public bool followAtStart = true;
    public Vector3 pinOffset;
    public Vector3 defaultRotation;
    public Transform followTarget;
    public bool isLookAt = false;
    public float followLerpSpeed = 2;
    private float followLerpSpeedPlus = 1.0f;
    private bool isFollow = false;



    private void Start()
    {
        if (followAtStart && followTarget)
        {
            Follow(followTarget, new Vector3(0, 0, 0));
        }
    }

    public void Follow(Transform target, Vector3 offset)
    {
        followTarget = target;
        // pinOffset = offset;
        isFollow = true;
    }

    public void UnFollow()
    {
        followTarget = null;
        pinOffset = new Vector3(0, 0, 0);
        isFollow = false;
    }

    public void ForceSetPostion()
    {
        var targetPosition = Quaternion.AngleAxis(followTarget.eulerAngles.y, Vector3.up) * (pinOffset) + followTarget.position;
        transform.position = targetPosition;
    }

    public void SetLookAtDelay(float time)
    {
        isLookAt = true;
        Invoke("SetLookAtDefault", time);
    }

    public void SetRotateSpeedUp(float time)
    {
        followLerpSpeedPlus = 5f;
        Invoke("SetRotateLerpDefault", time);
    }

    void SetLookAtDefault()
    {
        isLookAt = false;
    }

    void SetRotateLerpDefault()
    {
        followLerpSpeedPlus = 1f;
    }



    // Update is called once per frame
    void LateUpdate()
    {
        if (!followTarget || !isFollow) return;
        var targetPosition = Quaternion.AngleAxis(followTarget.eulerAngles.y, Vector3.up) * (pinOffset) + followTarget.position;

        var euler = Quaternion.LookRotation(followTarget.forward, Vector3.up).eulerAngles;
        var lerpValue = followLerpSpeed * followLerpSpeedPlus;

        if (isLookAt)
        {
            transform.LookAt(followTarget, Vector3.up);
        }
        else
        {

            var targetRotate = new Vector3(defaultRotation.x, euler.y, defaultRotation.z);
            transform.eulerAngles = new Vector3(
                Mathf.LerpAngle(transform.eulerAngles.x, targetRotate.x, Time.deltaTime * lerpValue),
                Mathf.LerpAngle(transform.eulerAngles.y, targetRotate.y, Time.deltaTime * lerpValue),
                Mathf.LerpAngle(transform.eulerAngles.z, targetRotate.z, Time.deltaTime * lerpValue)
            );
            //Vector3.LerpUnclamped(transform.eulerAngles,targetRotate,Time.deltaTime*lerpValue);

        }


        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * lerpValue);
    }


}
